#Author http://www.cnblogs.com/Jame-mei
import os
import paramiko


def connect_run_interface(host_info,command):
    '''
    1.batch run shell命令调取系统执行部分
    :param host_info:
    :param command:
    :return:
    '''
    ip=host_info['ip']
    port=host_info['port']
    username=host_info['username']
    passwd=host_info['password']


    #连接服务器
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip,port=port,username=username,password=passwd)

    #远程执行命令
    stdin,stdout,stderr=ssh.exec_command(command)


    #获取命令执行结果
    if not stderr:
        result=stdout.read()

    else:
        result=stdout.read()+stderr.read()

    print(ip.center(80,'-'))
    print(result.decode('utf-8'))

    #最后关闭连接
    ssh.close()



def connect_scp_interface(hostinfo,command):
    '''
    2.batch_scp 调取paramiko执行上传下载功能
    :param hostinfo:
    :param command:
    :return:
    '''


    transport=paramiko.Transport((hostinfo['ip'],hostinfo['port']))
    transport.connect(username=hostinfo['username'],password=hostinfo['password'])

    sftp=paramiko.SFTPClient.from_transport(transport)
    if command['-action']=='put':
        print(command['-local'],command['-remote'])
        sftp.put(command['-local'],command['-remote'])

    else:
        sftp.get(command['-remote'],command['-local'])


    transport.close()
